package com.leiqichao.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leiqichao.backend.common.Page;
import com.leiqichao.backend.entity.Article;
import com.leiqichao.backend.entity.LeaveMessage;
import com.leiqichao.backend.interceptor.StatsInterceptor;
import com.leiqichao.backend.mapper.LeaveMessageMapper;
import com.leiqichao.backend.service.LeaveMessageService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LeaveMessageServiceImpl extends ServiceImpl<LeaveMessageMapper, LeaveMessage> implements LeaveMessageService {


    @Override
    public Map<String, Object> saveleaveMessage(LeaveMessage leaveMessage) {
        Map<String, Object> map = new HashMap<>();

        // 检查当日留言次数
        QueryWrapper<LeaveMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ip", leaveMessage.getIp())
                .apply("DATE(timestamp) = CURDATE()"); // 使用日期函数获取当前日期


        Long count = baseMapper.selectCount(queryWrapper);

        if (count >= 3) {
            map.put("message", "今日留言已达3次上限，请明天再来");
            map.put("code", 1);
            throw new RuntimeException("今日留言已达3次上限，请明天再来");
        }
        save(leaveMessage);
        count++;
        map.put("message", "今日留言已达"+count+"次，每日可留言3次");
       map.put("code", 0);
        return map;
    }

    @Override
    public boolean update(LeaveMessage leaveMessage) {
        if (leaveMessage != null) {
            return updateById(leaveMessage);
        }
        return false;
    }

    @Override
    public boolean remove(String id) {
        if (id != null) {
            return removeById(id);
        }
        return false;
    }

    @Override
    public LeaveMessage get(String id) {
        if (id != null) {
            return getById(id);
        }
        return null;
    }

    @Override
    public Page getAllLeaveMessages(Page<LeaveMessage> page) {
        // 查询总记录数
        Long total = baseMapper.selectCount(new QueryWrapper<LeaveMessage>());
        page.setTotal(Math.toIntExact(total));
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("timestamp");
        // 查询当前页的数据
        Page<LeaveMessage> leaveMessage = baseMapper.selectPage(page,queryWrapper);
      


        return leaveMessage;
    }

}
